package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.customer.enums.CertificationAuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.WorkerCertificationAuditMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.domain.WorkerCertification;
import com.jzo2o.customer.model.domain.WorkerCertificationAudit;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.WorkerCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.response.WorkerCertificationAuditResDTO;
import com.jzo2o.customer.service.IWorkerCertificationAuditService;
import com.jzo2o.customer.service.IWorkerCertificationService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 * 服务人员认证信息审核表 服务实现类
 * </p>
 *
 * @author xuchun
 * @since 2024-08-12
 */
@Service
public class WorkerCertificationAuditServiceImpl extends ServiceImpl<WorkerCertificationAuditMapper, WorkerCertificationAudit> implements IWorkerCertificationAuditService {

    @Resource
    private IWorkerCertificationService workerCertificationService;
    @Override
    @Transactional
    public void submitAudit(WorkerCertificationAuditAddReqDTO dto) {
        dto.setServeProviderId( UserContext.currentUserId() );
        //校验用户是否已经认证通过
        WorkerCertification workerCertification = workerCertificationService
                .lambdaQuery()
                .eq(WorkerCertification::getId, dto.getServeProviderId())
                //.eq(WorkerCertification::getCertificationStatus, CertificationStatusEnum.SUCCESS.getStatus())
                .one();
        if (workerCertification != null && workerCertification.getCertificationStatus() == CertificationStatusEnum.SUCCESS.getStatus()) {
            throw new ForbiddenOperationException("该用户已经认证通过");
        }
        //校验用户是否已经提交审核
        WorkerCertificationAudit workerCertificationAudit =
                this.lambdaQuery()
                .eq(WorkerCertificationAudit::getServeProviderId, dto.getServeProviderId())
                .eq(WorkerCertificationAudit::getCertificationStatus, CertificationStatusEnum.PROGRESSING.getStatus())
                .one();
        if (workerCertificationAudit != null) {
            throw new ForbiddenOperationException("该用户已经提交审核，请勿重复提交");
        }
        workerCertificationAudit = BeanUtil.copyProperties(dto, WorkerCertificationAudit.class);
        workerCertificationAudit.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        workerCertificationAudit.setAuditStatus(CertificationAuditStatusEnum.NOT_AUDIT.getStatus());
        boolean result = this.save(workerCertificationAudit);
        if (!result) {
            throw new ForbiddenOperationException("提交审核失败");
        }
        workerCertificationService.removeById( dto.getServeProviderId() );
        workerCertification = BeanUtil.copyProperties(dto, WorkerCertification.class);
        workerCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        workerCertification.setId(dto.getServeProviderId());
        workerCertificationService.save(workerCertification);
    }

    @Override
    public Map<String, String> getRejectReason() {
        WorkerCertificationAudit workerCertificationAudit =
                this.lambdaQuery()
                .eq(WorkerCertificationAudit::getAuditStatus, CertificationAuditStatusEnum.AUDITED.getStatus())
                .eq(WorkerCertificationAudit::getCertificationStatus, CertificationStatusEnum.FAIL.getStatus())
                .eq(WorkerCertificationAudit::getServeProviderId, UserContext.currentUserId())
                .orderByDesc(WorkerCertificationAudit::getAuditTime)
                .last(" limit 1")
                .one();
        if (workerCertificationAudit != null) {
            return Map.of("rejectReason", workerCertificationAudit.getRejectReason());
        }
        return null;
    }

    @Override
    public PageResult<WorkerCertificationAuditResDTO> queryPage(WorkerCertificationAuditPageQueryReqDTO pageDTO) {
        Page<WorkerCertificationAudit> page = PageUtils.parsePageQuery(pageDTO, WorkerCertificationAudit.class);
        baseMapper.selectPage(page,
                Wrappers.<WorkerCertificationAudit>lambdaQuery()
                        .eq(pageDTO.getAuditStatus()!=null,WorkerCertificationAudit::getAuditStatus, pageDTO.getAuditStatus())
                        .eq(pageDTO.getCertificationStatus()!=null,WorkerCertificationAudit::getCertificationStatus, pageDTO.getCertificationStatus())
                        .like(StrUtil.isNotEmpty(pageDTO.getName()),WorkerCertificationAudit::getName,pageDTO.getName())
                        .like(StrUtil.isNotEmpty(pageDTO.getIdCardNo()),WorkerCertificationAudit::getIdCardNo,pageDTO.getIdCardNo())
        );
        return PageUtils.toPage(page, WorkerCertificationAuditResDTO.class);
    }

    @Override
    @Transactional
    public void audit(Long id, Integer certificationStatus, String rejectReason) {
        WorkerCertificationAudit workerCertificationAudit = getById(id);
        if (workerCertificationAudit == null) {
            throw new ForbiddenOperationException("审核信息不存在");
        }
        if (CertificationAuditStatusEnum.AUDITED.getStatus() == workerCertificationAudit.getAuditStatus()) {
            throw new ForbiddenOperationException("该信息已经审核结束");
        }
        boolean update = this.lambdaUpdate()
                .eq(WorkerCertificationAudit::getId, id)
                .set(WorkerCertificationAudit::getAuditStatus, CertificationAuditStatusEnum.AUDITED.getStatus())
                .set(WorkerCertificationAudit::getCertificationStatus, certificationStatus)
                .set(StrUtil.isNotEmpty(rejectReason), WorkerCertificationAudit::getRejectReason, rejectReason)
                .set(WorkerCertificationAudit::getAuditorId, UserContext.currentUserId())
                .set(WorkerCertificationAudit::getAuditorName, UserContext.currentUser().getName())
                .set(WorkerCertificationAudit::getAuditTime, LocalDateTime.now())
                .update();
        if (!update) {
            throw new ForbiddenOperationException("审核失败");
        }
        //更新认证信息
        boolean result  = workerCertificationService
                .lambdaUpdate().eq(WorkerCertification::getId, workerCertificationAudit.getServeProviderId())
                .set(WorkerCertification::getCertificationStatus, certificationStatus)
                .update();
        if (!result){
            throw new ForbiddenOperationException("保存认证信息失败");
        }
    }
}
